package cn.yunyichina.provider.clinic.listener;

import cn.yunyichina.provider.clinic.dao.FuyinApplyDao;
import cn.yunyichina.provider.framework.dubbo.service.BaseService;
import cn.yunyichina.provider.framework.dubbo.service.HisifaceService;
import cn.yunyichina.provider.framework.dubbo.service.MessageService;
import cn.yunyichina.provider.framework.dubbo.service.PayService;
import cn.yunyichina.provider.framework.exception.CallException;
import cn.yunyichina.provider.iface.entity.base.OrderExtVo;
import cn.yunyichina.provider.iface.entity.common.ResCommon;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.provider.iface.entity.hisiface.bed.PayDepositVo;
import cn.yunyichina.provider.iface.entity.hisiface.bed.PayDepositVoResponse;
import cn.yunyichina.provider.iface.entity.pay.PaymentJournalVo;
import cn.yunyichina.utils.commons.DateUtils;
import cn.yunyichina.utils.convert.JsonUtils;
import cn.yunyichina.utils.convert.XmlUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.listener.MessageListener;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CopyAliPayMessageListener implements MessageListener<Integer, String> {

    private Logger logger = LoggerFactory.getLogger(CopyAliPayMessageListener.class);

    @Autowired
    private FuyinApplyDao fuyinApplyDao;

    private final static String TRADE_IS_SUCCESS = "SUCCESS";

    private final static String TRADE_TYPE_APP = "APP";

    public void onMessage(ConsumerRecord<Integer, String> integerStringConsumerRecord) {
        logger.info("CopyAliPayMessageListener onMessage start.");

        String jsonString = integerStringConsumerRecord.value();
        logger.info("CopyAliPayMessageListener.onMessage.jsonString -> {}", jsonString);

        OrderExtVo updateOrderExtVo = new OrderExtVo();

        try {
            JSONObject jsonObject = JSON.parseObject(jsonString);
            String appId = (String) jsonObject.get("app_id");//应用ID
            String orderNo = (String) jsonObject.get("out_trade_no");//商户订单号
            String payStatus = (String) jsonObject.get("trade_status");//交易状态
            String paymentDealId = (String) jsonObject.get("trade_no");//第三方支付公司交易流水号
            String openId = (String) jsonObject.get("buyer_id");//用户openid
            String payCode = (String) jsonObject.get("pay_code");//支付编码
            String payMode = (String) jsonObject.get("pay_mode");//支付渠道
            //兼容支付宝更改后payMode节点位置变化的问题
            if(StringUtils.isBlank(payMode)){
                String passbackParams = (String) jsonObject.get("passback_params");
                logger.info("CopyAliPayMessageListener.onMessage.passbackParams -> {}", passbackParams);
                JSONObject jsonParams = JSON.parseObject(passbackParams);
                payCode = (String) jsonParams.get("pay_code");
                payMode = (String) jsonParams.get("pay_mode");
            }

            //一、处理order订单
            //查询订单
            Map<String, String> updateDataMap = new HashMap<String, String>();
            updateDataMap.put("order_no", orderNo);
            logger.info("【病案复印支付宝支付监听-查询订单信息】, yyt.base.order.by.order.no.out.get request=" + JSON.toJSONString(updateDataMap));
            Response ordUpdateResponse = BaseService.callUnderlineFromInternal("yyt.base.order.by.order.no.out.get",
                    JsonUtils.toJsonString(updateDataMap));
            logger.info("【病案复印支付宝监听-查询订单信息】, yyt.base.order.by.order.no.out.get response=" + JSONObject.toJSONString(ordUpdateResponse));
            if (!"0".equals(ordUpdateResponse.getResultCode())) {
                throw new CallException("14010","not found order by order_no=" + orderNo);
            }
            updateOrderExtVo = JsonUtils.parseObject(ordUpdateResponse.getResult(), OrderExtVo.class);

            if(TRADE_IS_SUCCESS.equalsIgnoreCase(payStatus)){
                logger.info("onMessage, 支付成功，start");//支付成功
                updateOrderExtVo.setPayStatusPayed();//支付成功
            }else{
                updateOrderExtVo.setPayStatusFail();//支付失败
            }
            updateOrderExtVo.setPayAppId(appId);
            updateOrderExtVo.setOpenId(openId);
            updateOrderExtVo.setPaymentDealId(paymentDealId);
            updateOrderExtVo.setIsInsurance((short) 0);
            updateOrderExtVo.setPayCode(payCode);
            updateOrderExtVo.setPayMode(Short.parseShort(payMode));
            updateOrderExtVo.setPayStatus((short)3);
            updateOrderExtVo.setOrderStatus((short)3);
            updateOrderExtVo.setIsPayHandled(1);
            updateOrderExtVo.setUpdateTime(DateUtils.dateToString(new Date()));
            updateOrderExtVo.setPayTime(DateUtils.dateToString(new Date()));
            logger.info("【病案复印支付宝支付监听-保存订单信息】, updateOrderExtVo=" + JSONObject.toJSONString(updateOrderExtVo));
            //保存订单信息
            BaseService.callUnderlineFromInternal("yyt.base.order.update", JsonUtils.toJsonString(updateOrderExtVo));


            //二、处理biz_fuyin_apply订单
            Map<String, Object> paramMap = new HashMap<>();
            try {
                paramMap.put("payStatus", "1");
                paramMap.put("payContent", "支付成功，更新订单状态成功");
                paramMap.put("orderNo", orderNo);
                paramMap.put("agtOrderNum", paymentDealId);
                paramMap.put("appId", appId);
                logger.info("【病案复印支付宝支付监听-保存biz_fuyin_apply信息】, paramMap=" + JSONObject.toJSONString(paramMap));
                fuyinApplyDao.updateByOrderNo(paramMap);
                logger.info("【病案复印支付宝支付监听-保存biz_fuyin_apply信息】, 支付成功，更新订单状态成功。");
            } catch (Exception ex) {
                paramMap.put("payStatus", "3");
                paramMap.put("payContent", "支付成功，更新订单状态失败");
                paramMap.put("orderNo", orderNo);
                paramMap.put("agtOrderNum", paymentDealId);
                paramMap.put("appId", appId);
                logger.info("【病案复印支付宝支付监听-保存biz_fuyin_apply信息】, paramMap=" + JSONObject.toJSONString(paramMap));
                fuyinApplyDao.updateByOrderNo(paramMap);
                logger.error("【病案复印支付宝支付监听-保存biz_fuyin_apply信息】, 支付成功，更新订单状态失败。", ex);
            }

        } catch (Exception e) {
            logger.error("onMessage error.", e);
        }

        logger.info("CopyAliPayMessageListener onMessage end.");
    }

}
